using System.Xml.Serialization;

namespace A1;

public class OrderService
{
    private readonly List<Order> _orders = new List<Order>();

    public void AddOrder(Order order)
    {
        if (_orders.Any(o => o.OrderId == order.OrderId))
        {
            throw new Exception("Order with the same ID already exists.");
        }
        _orders.Add(order);
    }

    public void RemoveOrder(int orderId)
    {
        var order = _orders.FirstOrDefault(o => o.OrderId == orderId);
        if (order != null)
        {
            _orders.Remove(order);
        }
        else
        {
            throw new Exception("Order not found.");
        }
    }

    public void ReplaceOrder(int orderId, Order newOrder)
    {
        var index = _orders.FindIndex(o => o.OrderId == orderId);
        if (index != -1)
        {
            _orders[index] = newOrder;
        }
        else
        {
            throw new Exception("Order not found to replace.");
        }
    }

    public IEnumerable<Order> QueryOrders(Func<Order, bool> predicate)
    {
        return _orders.Where(predicate).OrderBy(order => order.TotalAmount);
    }

    public void DisplayAllOrders()
    {
        if (!_orders.Any())
        {
            Console.WriteLine("No orders available.");
            return;
        }
    
        Console.WriteLine("All current orders:");
        foreach (var order in _orders)
        {
            Console.WriteLine(order);
            Console.WriteLine("------------------------------------------------");
        }
    }

    public void Export(string filePath)
    {
        var xmlSerializer = new XmlSerializer(typeof(List<Order>));
        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            xmlSerializer.Serialize(fileStream, _orders);
        }
    }

    public void Import(string filePath)
    {
        var xmlSerializer = new XmlSerializer(typeof(List<Order>));
        
        using (var fileStream = new FileStream(filePath, FileMode.Open))
        {
            var importedOrders = (List<Order>)xmlSerializer.Deserialize(fileStream)!;
            foreach (var order in importedOrders)
            {
                AddOrder(order); // This will check for duplicates based on OrderId
            }
        }
    }
    
    public List<Order> GetAllOrders() => _orders.OrderBy(order => order.OrderId).ToList();
}